import { login } from '@/services/admin'
import { message }  from 'antd'
import { history, Effect, Reducer } from 'umi'
export interface IUserState {
  adminname: string
  token: string
  role: number | string
  isLogin: boolean
}
export interface IUserModel {
  namespace: 'user',
  state: IUserState,
  effects: {
    loginEffect: Effect
  },
  reducers: {
    changeAdminName: Reducer,
    changeToken: Reducer,
    changeRole: Reducer,
    changeLoginState: Reducer,
  }
}

const userModel: IUserModel = {
  namespace: 'user',
  state: {
    adminname: localStorage.getItem('adminname') || '',
    token: localStorage.getItem('token') || '',
    role: localStorage.getItem('role') || 1,
    isLogin: localStorage.getItem('isLogin') === 'true' || false
  },
  effects: {
    * loginEffect ({ payload }: any, { call, put }: any) {
      const res = yield call(login, payload)

      if (res.data.code === '10005') {
        message.error('账户未注册')
      } else if (res.data.code === '10003') {
        message.error('密码错误')
      } else {
        message.success('登录')
        // 修改状态 ---- 必须使用 yield 表示代码的继续执行
        // 使用时必须是对象形式
        yield put({ type: 'changeAdminName', payload: res.data.data.adminname})
        yield put({ type: 'changeToken', payload: res.data.data.token})
        yield put({ type: 'changeRole', payload: res.data.data.role})
        yield put({ type: 'changeLoginState', payload: true})

        localStorage.setItem('adminname', res.data.data.adminname)
        localStorage.setItem('token', res.data.data.token)
        localStorage.setItem('role', res.data.data.role )
        localStorage.setItem('isLogin', 'true')
        history.push('/')
      }

    }
  },
  reducers: {
    changeAdminName (state: any, action: any) {
      state.adminname = action.payload
    },
    changeToken (state: any, action: any) {
      state.token = action.payload
    },
    changeRole (state: any, action: any) {
      state.role = action.payload
    },
    changeLoginState (state: any, action: any) {
      state.isLogin = action.payload
    }
  }
}

export default userModel
